import React from 'react'
import { Link } from 'react-router-dom'
import routeConfig from './routeConfig'

/**
 * 根据name获取path
 * @param {*} name
 */
function getPath(name, baseUrl, routesArr) {
    for (const routes of routesArr) {
        let newPath = baseUrl + routes.path
        if (routes.name === name) {
            return newPath
        } else if (Array.isArray(routes.children)) {
            const path = getPath(name, newPath, routes.children)
            if (path) return path
        }
    }
}

/**
 * 增强Link功能 
 * @export
 * @return {*} 
 */
export default function BetterLink(props = {}) {
    const { to, children, ...rest } = props
    if (to.name && typeof to !== 'string') {
        to.pathname = getPath(to.name, '', routeConfig)
        if (to.pathnam) {
            throw new Error(`name属性值【${to.name}】无效`)
        }
    }
    return (
        <Link to={to} {...rest}>
            {children}
        </Link>
    )
}
